<?php

include 'bur_controller.php';

class Detail_payment_plan extends Bur_controller {
	
	function index()
	{
		$this->view();
	}
	
	function view($nim = NULL, $bulan = NULL, $semester = NULL)
	{							
		$this->_entry($nim, $bulan, $semester, true, true);
	}
	
	function _report_meta($nim, $bulan, $semester)
	{

		$nama = $this->_name($nim);
		$angkatan = $this->_peer_year($nim);
		$tahun_ajaran = $this->_acd_year_desc_from_semester($semester);
		
		$tanggal = mdate("%d/%m/%Y", now());;
		$penerima = '';		
		
		return array(
			'nim' => $nim,
			'nama' => $nama,
			'tahun_ajaran' => $tahun_ajaran,
			'angkatan' => $angkatan,		
			'tanggal' => $tanggal,
			'penerima' => $penerima,			
		);
	}
	
	function _report($nim, $bulan, $semester, $n_copy)
	{
		return array(
			'n_copy' => $n_copy,	
			'meta' => $this->_report_meta($nim, $bulan, $semester),
			'data' => $this->_payment_plan_data($nim, $bulan, $semester),			
		);
	}
	
	function report($type = 'html', $n_copy = 2, $nim = NULL, $bulan = NULL, $semester = NULL)
	{
		if ($this->_is_student()) { // current role = mahasiswa
			$user = $this->common->current_user_key();
			$nim = $this->_user_student_id($user);
		}
		
		if (is_null_or_false($n_copy)) {
			$n_copy = 2;
		}
		
		if (is_null_or_false($bulan)) {
			$bulan = $this->_current_month();
		}
		
		if (is_null_or_false($semester)) {
			$semester = $this->_current_semester();
		}
		
		$content_data = $this->_report($nim, $bulan, $semester, $n_copy);
	
		switch ($type) {
			case 'pdf':
				$name .= $nim.'_'.now();
				$name .= '.pdf';
				$mpdf = new mPDF();
				$mpdf->WriteHTML($this->load->view('bur/report/lembar_kontrol_pembayaran', $content_data, true));
				$mpdf->Output($name, 'D');
				break;
			case 'html':
				$data = array(
					'content' => $this->load->view('bur/report/lembar_kontrol_pembayaran', $content_data, TRUE),
				);
				
				$this->load->view('layout/plain', $data);
				break;
		}
		
		//if status == 'new', set status as 'printed'
		$this->_set_status('payment_plan', $nim, $bulan, $semester, 'printed', 'new');
	}
	
	function batch_report($type = 'html', $n_copy = 2, $bulan = NULL, $semester = NULL)
	{
		// this function receives array of NIM from $_POST['students']
			
		if (is_null_or_false($n_copy)) {
			$n_copy = 2;
		}
		
		if (is_null_or_false($bulan)) {
			$bulan = $this->_current_month();
		}
		
		if (is_null_or_false($semester)) {
			$semester = $this->_current_semester();
		}
		
		$students = $this->input->post('students');
		
		if (!$students) {
			$students = $this->_students_with_plan_id($bulan, $semester);
		}		
		if ($type == 'pdf') {
			$time = now();

			$time_limit = 0;
			set_time_limit($time_limit);
			ini_set('max_execution_time', $time_limit);
			ini_set('memory_limit', '256M');
			
			$name = $time.'.pdf';
			
			$mpdf = new mPDF();
			
			$i = 0;
			$n = count($students);
			foreach($students as $idx => $nim) {
				//set status as printed
				$this->_set_status('payment_plan', $nim, $bulan, $semester, 'printed', 'new');
			
				$content_data = $this->_report($nim, $bulan, $semester, $n_copy);
				$mpdf->WriteHTML($this->load->view('bur/report/lembar_kontrol_pembayaran', $content_data, true));
				if (++$i != $n) {
					$mpdf->AddPage();
				}			
			}
			
			$mpdf->Output($name, 'D');
		} else if ($type == 'zip') {
			$time = now();

			$time_limit = 0;
			set_time_limit($time_limit);
			ini_set('max_execution_time', $time_limit);
			ini_set('memory_limit', '256M');
			
			$this->zip->clear_data(); 
			
			foreach($students as $idx => $nim) {
				//set status as printed
				$this->_set_status('payment_plan', $nim, $bulan, $semester, 'printed', 'new');
				
				$mpdf = new mPDF();

				$name = $nim.'.pdf';
				$content_data = $this->_report($nim, $bulan, $semester, $n_copy);
				$mpdf->WriteHTML($this->load->view('bur/report/lembar_kontrol_pembayaran', $content_data, true));
				
				$data = $mpdf->Output('', 'S');
				
				$this->zip->add_data($name, $data); 
			}
						
			$this->zip->download($time.'.zip'); 			
		} else {
			foreach($students as $idx => $nim) {
				//set status as printed
				$this->_set_status($nim, $bulan, $semester, 'printed', 'new');
				
				$this->report($type, $n_copy, $nim, $bulan, $semester);
			}
		}
	}
	
	function __entry($nim, $bulan, $semester, $update, $readonly) {

		$nama = $this->_name($nim);
		$angkatan = $this->_peer_year($nim);
		
		$prodi = $this->_study_program($nim);
	
		$semester_desc = $this->_current_semester_desc();		

		$payment_plan_id = $this->_payment_plan_id($nim, $bulan, $semester);		
		$result = $this->model->get_data_from_query('*', array('id_bur_payment_plan' => $payment_plan_id), NULL, NULL, NULL, NULL, 'bur_t_detail_payment_plan');
	
		$referrer = $this->input->post('__referrer');
		if (!$referrer)
			$referrer = $this->agent->referrer();
	
		// sudah entry bursar? jika sudah dan $update=false, redirect ke update. jika belum dan $update=true, redirect ke add.		
		if ((count($result)>0) && !$update) {
			$this->common->flash_message('Data sudah ada, silakan meng-update data jika perlu.', 1);
			$this->session->set_flashdata('referrer', $referrer);
			redirect(get_unit_controller($this).'/update/'.$nim.'/'.$bulan.'/'.$semester);
		} else if ((count($result)<=0) && $update) {
			$this->common->flash_message('Silakan mengisi data bursar terlebih dahulu.', 1);
			$this->session->set_flashdata('referrer', $referrer);
			redirect(get_unit_controller($this).'/add/'.$nim.'/'.$bulan.'/'.$semester);
		}
	
		if ($update) {
			$detail_payment_plan = $result;
			reset($result);
			
			$status = $this->common->get_field_from_criteria('bur_h_payment_plan', 'key_bur_payment_plan_status', array('key_aka_student' => $nim, 'key_aka_semester' => $semester, 'month' => intval($bulan)));

			$_readonly = ((($this->_is_student()) && (strcasecmp($status, 'new')!=0)) || (strcasecmp($status, 'processed')==0));
			if ($_readonly && !$readonly) {
				$this->common->flash_message('Data bursar telah diproses sehingga tidak boleh di-edit.', 1);
				$this->session->set_flashdata('referrer', $referrer);
				redirect(get_unit_controller($this).'/view/'.$nim.'/'.$bulan.'/'.$semester);
			}
		}
		
		
		$result = $this->model->get_data_from_query(array('id', 'key', 'description'), NULL, NULL, NULL, NULL, NULL, 'bur_r_payment_type');		
		
		$charge_id = $this->_charge_id($nim, $bulan, $semester);
		$detail_charge = $this->model->get_data_from_query(array('key_bur_payment_type', 'outstanding', 'interest', 'new_charge', 'minimum_payment'), array('id_bur_charge' => $charge_id), NULL, NULL, NULL, NULL, 'bur_t_detail_charge');		
		
		//print_r_pre($detail_charge);
		
		$tabel = array();

		// $_result contains payment plan data
		
		$total_tunggakan = 0;
		$total_kewajiban = 0;
		$total_denda = 0;
		$total_minimal = 0;
		
		foreach($result as $idx => $val) {
			if ($val['id']==0) continue;	// skip biaya 'lain-lain' (idx 0)
			
			$rp = 0;
			$ket = '';
			
			$tunggakan = '';
			$kewajiban = '';
			$denda = '';
			$minimal = '';
			
			foreach ($detail_charge as $_idx => $_val) {
				if ($_val['key_bur_payment_type'] == $val['key']) {
					$tunggakan = round($_val['outstanding'], 2);
					$kewajiban = round($_val['new_charge'], 2);
					$denda = round($_val['interest'], 2);
					$minimal = round($_val['minimum_payment'], 2);
					$total_tunggakan += $tunggakan;
					$total_kewajiban += $kewajiban;
					$total_denda += $denda;
					$total_minimal += $minimal;
					break;
				}
			}
			
			if ($update) {
				foreach ($detail_payment_plan as $_idx => $_val) {
					if ($_val['key_bur_payment_type'] == $val['key']) {
						$rp = round($_val['total'], 2);
						$ket = $_val['remark'];
						break;
					}
				}
			}
			
			$tabel[] = array('biaya' => $val['description'], 'key_biaya' => $val['key'], 'rp' => $rp, 'keterangan' => $ket, 'tunggakan' => $tunggakan, 'kewajiban' => $kewajiban, 'denda' => $denda, 'minimal' => $minimal);
		}
		
		
		// tambahkan biaya 'lain-lain' (idx 0) ke bagian bawah tabel
		$val = $result[0];
		
		$rp = 0;
		$ket = '';
		
		$tunggakan = '';
		$kewajiban = '';
		$denda = '';
		$minimal = '';
		
		foreach ($detail_charge as $_idx => $_val) {
			if ($_val['key_bur_payment_type'] == $val['key']) {
				$tunggakan = round($_val['outstanding'], 2);
				$kewajiban = round($_val['new_charge'], 2);
				$denda = round($_val['interest'], 2);
				$minimal = round($_val['minimum_payment'], 2);
				$total_tunggakan += $tunggakan;
				$total_kewajiban += $kewajiban;
				$total_denda += $denda;
				$total_minimal += $minimal;
				break;
			}
		}
		
		if ($update) {
			foreach ($detail_payment_plan as $_idx => $_val) {
				if ($_val['key_bur_payment_type'] == $val['key']) {
					$rp = round($_val['total'], 2);
					$ket = $_val['remark'];
					break;
				}
			}
		}
		
		$tabel[] = array('biaya' => $val['description'], 'key_biaya' => $val['key'], 'rp' => $rp, 'keterangan' => $ket, 'tunggakan' => $tunggakan, 'kewajiban' => $kewajiban, 'denda' => $denda, 'minimal' => $minimal);
										
		$referrer = $this->session->flashdata('referrer');
		if (!$referrer)
			$referrer = $this->agent->referrer();
										
		$content_data = array(
			'nama' =>  $nama,
			'nim' => $nim,
			'angkatan' => $angkatan,
			'prodi' => $prodi,
			'semester' => $semester,
			'semester_desc' => $semester_desc,
			'bulan' => $bulan,
			'tabel' => $tabel,
			'total_tunggakan' => $total_tunggakan,
			'total_kewajiban' => $total_kewajiban,
			'total_denda' => $total_denda,
			'total_minimal' => $total_minimal,
			'readonly' => $readonly,
			'referrer' => $referrer,			
		);
				
		$data = array(
		'application' => get_application($this),
		'application_title' => $this->common->get_application_description(get_application($this)),
		'page' => 'Entry Data Bursar',
		'navigation' => $this->_navigation(),
		'content' => $this->load->view('bur/form/payment_plan_entry', $content_data, TRUE),
		);
	
		$this->load->view('layout/default', $data);
	}	
	
	function _entry($nim = NULL, $bulan = NULL, $semester = NULL, $update = false, $readonly = false) {

		if (is_null_or_false($bulan)) {	// if no month is specified, use current month
			$bulan = $this->_current_month();
		}
		
		if (is_null_or_false($semester)) { // if no semester is specified, use current semester
			$semester = $this->_current_semester();
		}
	
	
		if ($this->_is_student()) { // current role = mahasiswa, prevent accessing other student's data
			$user = $this->common->current_user_key();
			$nim = $this->_user_student_id($user);
			
			$this->__entry($nim, $bulan, $semester, $update, $readonly);
		} else {
			if (is_null_or_false($nim)) { //TODO:no nim specified, let the user choose
				$data = array(
				'application' => get_application($this),
				'application_title' => $this->common->get_application_description(get_application($this)),
				'page' => 'Entry Data Bursar',
				'navigation' => $this->_navigation(),
				'content' => '',
				);
			
				$this->load->view('layout/default', $data);			
			} else {
				$this->__entry($nim, $bulan, $semester, $update, $readonly);
			}			
		}
	}
	
	
	function add($nim = NULL, $bulan = NULL, $semester = NULL)
	{		
		$this->_entry($nim, $bulan, $semester);
	}

	function process_add()
	{
		$this->process_update();
	}
	
	function update($nim = NULL, $bulan = NULL, $semester = NULL)
	{							
		$this->_entry($nim, $bulan, $semester, true);
	}
	
	function process_update()
	{		
		$data = array();
		
		foreach($_POST as $idx => $val) {
			$jenis = array();
			$jenis[] = array('in' => 'key_biaya', 'db' => 'key_bur_payment_type');
			$jenis[] = array('in' => 'rp', 'db' => 'total');
			$jenis[] = array('in' => 'keterangan', 'db' => 'remark');

			foreach ($jenis as $tipe) {
				if (strpos($idx, $tipe['in'])===0) {
					$cidx = substr($idx, strrpos($idx, '_')+1);
					$data[$cidx][$tipe['db']] = $val;
				}
			}				
		}
		
		$nim = $this->input->post('nim');
		$bulan = $this->input->post('bulan');
		$semester = $this->input->post('semester');
		$payment_plan_id = $this->_payment_plan_id($nim, $bulan, $semester);
		
		if (!$payment_plan_id) {	// header belum ada, create header
			$header = array('key_aka_student' => $nim, 'key_aka_semester' => $semester, 'month' => $bulan,
							'key_bur_payment_plan_status' => 'new');
			$this->common->who_am_i($header, TRUE, 'crea');

			$this->model->add($header, 'bur_h_payment_plan');
			$payment_plan_id = $this->_payment_plan_id($nim, $bulan, $semester);
		}
		
		$total = 0;
		
		foreach($data as $idx => $val) {
			$data[$idx]['id_bur_payment_plan'] = $payment_plan_id;
			$total = $total + $val['total'];
		}
		
		// update total pada header
		$this->model->update(array('total' => $total), array('id' => $payment_plan_id), 'bur_h_payment_plan');
				
		$update = false;
		foreach($data as $idx => $val) {
			// cek apakah sudah ada
			$result = $this->model->get_data_from_query('*', array('id_bur_payment_plan' => $val['id_bur_payment_plan'], 'key_bur_payment_type' => $val['key_bur_payment_type']), NULL, NULL, NULL, NULL, 'bur_t_detail_payment_plan');
			
			if (count($result) == 0) {								
				$this->common->who_am_i($val, TRUE, 'crea');
				$this->model->add($val, 'bur_t_detail_payment_plan');
			} else {
				$record = (end($result));
				$this->common->who_am_i($val, TRUE, 'upd');
				$this->model->update($val, array('id' => $record['id']), 'bur_t_detail_payment_plan');
				$update = true;				
			}
		}
		
		if ($update) {	// update record
			$this->common->flash_message('Data bursar Anda telah di-update', -1);
		} else {	// new record
			$this->common->flash_message('Data bursar Anda telah tersimpan di database', -1);
		}
		
		if ($this->input->post('__referrer')) {
			redirect($this->input->post('__referrer'));
		} else {
			$this->_self_redirect();
		}
	}
	
	function bulk_action()
	{
		$action = $this->input->post('__submit');
		$n_copy = $this->input->post('n_copy');
		$bulan = $this->input->post('bulan');
		$semester = $this->input->post('semester');
		
		switch($action) {
			case 'Download Kuitansi (PDF)':
				$this->batch_report('pdf', $n_copy, $bulan, $semester);
				break;
			case 'Download Kuitansi (ZIP)':
				$this->batch_report('zip', $n_copy, $bulan, $semester);
				break;
			case 'Proses Pembayaran':	
				$this->batch_confirm_payment($bulan, $semester);
				break;
		}
	}
	
	function batch_confirm_payment($bulan = NULL, $semester = NULL)
	{
		// this function receives array of NIM from $_POST['students']
		
		if (is_null_or_false($bulan)) {
			$bulan = $this->_current_month();
		}
		
		if (is_null_or_false($semester)) {
			$semester = $this->_current_semester();
		}
		
		$students = $this->input->post('students');
		
		foreach($students as $idx => $nim) {
			$this->_confirm_payment($nim, $bulan, $semester);
		}
		
		if ($this->input->post('__referrer')) {
			redirect($this->input->post('__referrer'));
		} else {
			redirect($this->agent->referrer());
		}
	}
	
	function confirm_payment($nim = NULL, $bulan = NULL, $semester = NULL)
	{
		if (is_null_or_false($bulan)) {	// if no month is specified, use current month
			$bulan = $this->_current_month();
		}
		
		if (is_null_or_false($semester)) { // if no semester is specified, use current semester
			$semester = $this->_current_semester();
		}	
	
		if ($this->_is_student()) { // current role = mahasiswa, prevent accessing other student's data
			$user = $this->common->current_user_key();
			$nim = $this->_user_student_id($user);
			
			$this->_confirm_payment($nim, $bulan, $semester);
		} else {
			if (is_null_or_false($nim)) { //TODO:no nim specified, let the user choose
				$data = array(
				'application' => get_application($this),
				'application_title' => $this->common->get_application_description(get_application($this)),
				'page' => 'Konfirmasi Pembayaran Bursar',
				'navigation' => $this->_navigation(),
				'content' => '',
				);
			
				$this->load->view('layout/default', $data);			
			} else {
				$this->_confirm_payment($nim, $bulan, $semester);
			}			
		}
		
		if ($this->input->post('__referrer')) {
			redirect($this->input->post('__referrer'));
		} else {
			redirect($this->agent->referrer());
		}
	}
}
